package com.gack.netty.util.common;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.gack.netty.annotation.RequestMessageAnnotation;

/**
 * 
* @ClassName: ClassUtil 
* @Description: TODO(客户端请求消息注解类扫描工具  扫描包下添加了请求消息注解的类) 
* @author (ZhangXinYu)  
* @date 2018年8月31日 下午4:23:45 
* @version V1.0
 */
public class ServerMessageTypeToClassUtil {
	
	// 消息类型对应处理类
	private static Map<Integer, Class<?>> typeToMsgClassMap;
	
	// 根据消息类型获取对应处理类
	public static Class<?> getMsgClassByType(int type) {
		return typeToMsgClassMap.get(type);
	}
	
	// 初始化消息处理类  扫描注解 获取所有消息处理类
	public static void initTypeToMsgClassMap(String scanAnnotationPath) throws ClassNotFoundException, IOException{
		Map<Integer, Class<?>> tmpMap = new HashMap<Integer, Class<?>>();

		//get all class by classPath
		Set<Class<?>> classSet = new HashSet<>(ClassUtil.getClasses(scanAnnotationPath));
		// get serviceClass and msgType by annotation
		if(classSet != null){
			for(Class<?> clazz : classSet){
				if(clazz.isAnnotationPresent(RequestMessageAnnotation.class)){
					RequestMessageAnnotation annotation = clazz.getAnnotation(RequestMessageAnnotation.class);
					tmpMap.put(annotation.msgType(), clazz);
				}
			}
		}
		
		// add temp class to msgClass
		typeToMsgClassMap = Collections.unmodifiableMap(tmpMap);
	}
}
